import axios from 'axios';
import Vue from 'vue';
import qs from 'qs'

const baseUrl = 'http://localhost:8088/shareVue'
export default ({ method = "GET", url, data }) => {
  
  return new Promise((resolve, reject) => {
    // 处理登录超时
    const cookie = document.cookie || '';
    const cookieStr = cookie.replace(/; /gm, '&');
    const cookieObj = qs.parse(cookieStr);
    const userName = cookieObj.userName;
    if (!userName && location.pathname !== '/login') {
      Vue.prototype.$Message.error('登录超时，请前往登录');
      const timeOut = setTimeout(() => {
        location.href = '/login';
        clearTimeout(timeOut);
      }, 1000);
      return;
    }
    axios({
      url: `${baseUrl}${url}`,
      method,
      data,
      // 传递cookie所用
      withCredentials: true
    }).then((result) => {
      resolve(result.data);
    }).catch((err) => {
      reject(err);
    });
  })
}